package com.github.shiqiyue.blog.markdown.config.druid;

import java.sql.SQLException;
import java.util.Arrays;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.shiqiyue.blog.markdown.config.ApplicationConfig;

/***
 * druid 配置类
 * 
 * @author wwy
 *
 */
@Configuration
@EnableConfigurationProperties(ApplicationConfig.class)
public class DruidConfiguration {
	
	private DruidConfig druidConfig;
	
	private static final Logger LOG = LoggerFactory.getLogger(DruidConfiguration.class);
	
	public DruidConfiguration(ApplicationConfig applicationConfig) {
		this.druidConfig = applicationConfig.getDruid();
	}
	
	@Bean
	@Primary
	public DataSource druidDataSource() {
		DruidDataSource datasource = new DruidDataSource();
		datasource.setUrl(druidConfig.getUrl());
		datasource.setUsername(druidConfig.getUsername());
		datasource.setPassword(druidConfig.getPassword());
		datasource.setDriverClassName(druidConfig.getDriverClassName());
		datasource.setInitialSize(druidConfig.getInitialSize());
		datasource.setMinIdle(druidConfig.getMinIdle());
		datasource.setMaxActive(druidConfig.getMaxActive());
		datasource.setMaxWait(druidConfig.getMaxWait());
		datasource.setTimeBetweenEvictionRunsMillis(druidConfig.getTimeBetweenEvictionRunsMillis());
		datasource.setMinEvictableIdleTimeMillis(druidConfig.getMinEvictableIdleTimeMillis());
		datasource.setValidationQuery(druidConfig.getValidationQuery());
		datasource.setTestWhileIdle(druidConfig.isTestWhileIdle());
		datasource.setTestOnBorrow(druidConfig.isTestOnBorrow());
		datasource.setTestOnReturn(druidConfig.isTestOnReturn());
		datasource.setMaxOpenPreparedStatements(druidConfig.getMaxOpenPreparedStatements());
		datasource.setRemoveAbandoned(druidConfig.isRemoveAbandoned());
		datasource.setRemoveAbandonedTimeout(druidConfig.getRemoveAbandonedTimeout());
		datasource.setLogAbandoned(druidConfig.isLogAbandoned());
		datasource.setTimeBetweenLogStatsMillis(druidConfig.getTimeBetweenLogStatsMillis());
		datasource.setConnectionInitSqls(Arrays.asList("set names utf8mb4;"));
		try {
			datasource.setFilters(druidConfig.getFilters());
		} catch (SQLException e) {
			LOG.error("druid configuration initialization filter", e);
		}
		return datasource;
	}
	
}
